package com.gxa.filter;

//import com.gxa.utils.ResponseUtils;
import com.gxa.utils.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.List;

/**
 * 全局过滤器，这里拿来检查是否携带token
 */
//@Component
@Slf4j
public class AuthGlobalFilter02 implements GlobalFilter, Ordered {
    public Mono<Void> filter(ServerWebExchange exchange,GatewayFilterChain chain){
//获取token
        String token = exchange.getRequest().getHeaders().getFirst("token");
        //token为空
        if(StringUtils.isEmpty(token)){
            log.info("token is null");
            ServerHttpResponse response =exchange.getResponse();
            response.getHeaders().add("Content‐Type",
                        "application/json;charset=UTF‐8");
            //401用户没有访问权限
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            byte[] bytes = HttpStatus.UNAUTHORIZED.getReasonPhrase().getBytes();
            DataBuffer buffer = response.bufferFactory().wrap(bytes);
            //请求结束，不继续向下请求
            return response.writeWith(Mono.just(buffer));

        }
        //TODO 校验token进行身份认证
        log.info("校验token");

        //校验jwt是否正确，是否过期

        //交验完请求继续
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}